<template>
  <div class="app-container">
    <el-card class="header-container">
      <i class="el-icon-back" @click="$router.back(-1)" />
      <el-button v-permission="['training:exam:edit']" class="fr m-t-5 m-r-20" type="success" icon="el-icon-folder-add" @click="handleExam(undefined)">
        新建试卷
      </el-button>
    </el-card>

    <div class="left-menu-container">
      <el-menu :default-active="defaultActive" active-text-color="#409eff">
        <el-menu-item v-for="exam in examListData" :key="'exam_' + exam.examId">
                <span slot="title" @click="changeExam(exam)">
                  <el-tooltip class="item" :content="exam.title" placement="right">
                    <span>{{ exam.title }}</span>
                  </el-tooltip>
                </span>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="right-content-container">
      <el-card style="padding: 10px;">
        <el-row v-if="examInfo.examId" :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['training:exam:edit']" type="primary" size="mini" plain icon="el-icon-view" @click="handlePreviewExam(examInfo)">
              预览试卷
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['training:exam:edit']" type="primary" size="mini" plain icon="el-icon-plus" @click="handleExam(examInfo)">
              编辑试卷
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['training:exam:delete']" type="danger" size="mini" plain icon="el-icon-delete" @click="deleteExam()">
              删除试卷
            </el-button>
          </el-col>
          <el-button icon="el-icon-refresh" class="fr m-l-10" circle @click="getTableData"></el-button>
          <el-button v-permission="['training:exam:delete']" v-if="selectionData.length > 0" class="fr m-l-10" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDeleteQuestion()">
            删除考题
          </el-button>
          <el-button v-permission="['training:exam:edit']" class="fr" type="success" size="mini" plain icon="el-icon-plus" @click="handleQuestion(examInfo.examId)">
            添加考题
          </el-button>
        </el-row>
        <el-table
          ref="question_table"
          v-loading="tableLoading"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="题目" prop="content" sortable show-overflow-tooltip />
          <el-table-column align="center" label="类型" prop="type" sortable width="90">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.type == '0'" type="primary">单选</el-tag>
              <el-tag v-if="scope.row.type == '1'" type="primary">多选</el-tag>
              <el-tag v-if="scope.row.type == '2'" type="primary">判断</el-tag>
              <el-tag v-if="scope.row.type == '3'" type="primary">填空</el-tag>
              <el-tag v-if="scope.row.type == '4'" type="primary">主观</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="难度" prop="difficulty" sortable width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-rate disabled text-color="#ff9900" :value="scope.row.difficulty"></el-rate>
            </template>
          </el-table-column>
          <el-table-column align="center" label="分值" prop="score" width="90" show-overflow-tooltip />
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </div>

    <el-dialog v-el-drag-dialog :title="examTitle" :visible.sync="showExamDialog" :append-to-body="false">
      <el-form ref="examForm" :model="examInfo" label-width="120px">
        <el-card class="p-t-20 p-r-20">
          <el-form-item hidden>
            <el-input v-model="examInfo.examId" hidden/>
          </el-form-item>
          <el-form-item label="考试标题" prop="title">
            <el-input v-model="examInfo.title"/>
          </el-form-item>
          <el-form-item label="考试介绍" prop="introduce">
            <el-input v-model="examInfo.introduce" type="textarea" rows="2" />
          </el-form-item>
          <el-form-item label="题目乱序" prop="questionDisorder">
            <el-radio v-model="examInfo.questionDisorder" label="0">是</el-radio>
            <el-radio v-model="examInfo.questionDisorder" label="1">否</el-radio>
          </el-form-item>
          <el-form-item label="选项乱序" prop="optionDisorder">
            <el-radio v-model="examInfo.optionDisorder" label="0">是</el-radio>
            <el-radio v-model="examInfo.optionDisorder" label="1">否</el-radio>
          </el-form-item>
          <el-form-item label="行为监控" prop="isMonitor">
            <el-radio v-model="examInfo.isMonitor" label="0">是</el-radio>
            <el-radio v-model="examInfo.isMonitor" label="1">否</el-radio>
          </el-form-item>
          <el-form-item label="允许复制" prop="isCopyPaste">
            <el-radio v-model="examInfo.isCopyPaste" label="0">是</el-radio>
            <el-radio v-model="examInfo.isCopyPaste" label="1">否</el-radio>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="examInfo.startTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="examInfo.endTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-card>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-check" @click="onSaveExam">确 定</el-button>
        <el-button icon="el-icon-close" @click="onCloseExam">关 闭</el-button>
      </span>
    </el-dialog>

    <question-select-dialog v-if="openTreeDialog" ref="questionDialog" @confirmDialog="handleSaveExamQuestion" />
    <question-preview-dialog v-if="openPreviewDialog" ref="examPreviewDialog" />
  </div>
</template>

<script>
import {
  examList,
  examSave,
  examDelete,
  examQuestionTable,
  examQuestionAdd,
  examQuestionDelete
} from '@/api/training/exam'
import QuestionSelectDialog from '@/views/training/question/table/selectDialog'
import QuestionPreviewDialog from '@/views/training/exam/preview'

export default {
  name: 'ExamForm',
  components: {
    QuestionSelectDialog,
    QuestionPreviewDialog
  },
  data() {
    return {
      courseId: undefined,
      examTitle: '编辑试卷',
      examListData: [],
      showExamDialog: false,
      defaultActive: undefined,
      examInfo: {
        examId: undefined,
        courseId: undefined,
        title: undefined,
        introduce: undefined,
        questionDisorder: '0',
        optionDisorder: '1',
        startTime: undefined,
        endTime: undefined,
        isMonitor: '1',
        isCopyPaste: '1'
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      openTreeDialog: false,
      openPreviewDialog: false
    }
  },
  created() {
    this.courseId = this.$route.query.courseId
    this.$nextTick(() => {
      this.initExam()
    })
  },
  methods: {
    initExam() {
      this.examListData = []
      examList({Q_courseId_L_EQ: this.courseId}).then(response => {
        this.examListData = response
        if (this.examListData.length > 0) {
          this.defaultActive = 'exam_' + this.examListData[0].examId
          this.getExamInfo(this.examListData[0])
          this.getTableData()
        }
      })
    },
    changeExam(exam) {
      this.examInfo = exam
      this.getTableData()
    },
    getExamInfo(examInfo) {
      this.examInfo = examInfo || {
        examId: undefined,
        courseId: this.courseId,
        title: undefined,
        introduce: undefined,
        questionDisorder: '0',
        optionDisorder: '1',
        startTime: undefined,
        endTime: undefined,
        isMonitor: '1',
        isCopyPaste: '1'
      }
    },
    handleExam(examInfo) {
      this.getExamInfo(examInfo)
      this.showExamDialog = true
    },
    handlePreviewExam(examInfo) {
      this.openPreviewDialog = true
      this.$nextTick(() => {
        this.$refs.examPreviewDialog.init(examInfo.examId)
      })
    },
    getTableData() {
      this.tableLoading = true
      this.tableData = []
      examQuestionTable(this.examInfo.examId, this.tableQuery).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.question_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    onSaveExam() {
      examSave(this.examInfo).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.initExam()
        this.onCloseExam()
      })
    },
    onCloseExam() {
      this.$refs.examForm.resetFields()
      this.showExamDialog = false
    },
    handleQuestion() {
      this.openTreeDialog = true
      this.$nextTick(() => {
        this.$refs.questionDialog.init(this.examInfo.examId)
      })
    },
    handleSaveExamQuestion(nodes) {
      let questions = ''
      if (nodes.length > 0) {
        for (let i = 0; i < nodes.length; i++) {
          questions += nodes[i].questionId + ','
        }
      }

      if (questions.length > 0) {
        questions = questions.substring(0, questions.length - 1)
        examQuestionAdd(this.examInfo.examId, {
          ids: questions
        }).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.getTableData()
        })
      }
    },
    handleDeleteQuestion() {
      const ids = this.selectionData.map(function (question, index) {
        return question.questionId
      }).join(',')

      if (!ids || ids.length === 0) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选考题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        examQuestionDelete(this.examInfo.examId, {ids: ids}).then(response => {
          this.getTableData()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {
        })
      }).catch(e => {
      })
    },
    deleteExam() {
      this.$confirm(`是否删除试卷 [${this.examInfo.title}]?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        examDelete({
          ids: this.examInfo.examId
        }).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.getTreeData()
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 0;
}

::v-deep .el-menu {
  border: none;
  background-color: transparent;
}

.app-container {
  display: flex;
}

.header-container {
  width: calc(100% - 40px);
  height: 50px;
  padding: 0 20px;
  line-height: 50px;
  display: block;
  position: absolute;

  .el-icon-back {
    font-size: 22px;
    font-weight: 550;
    cursor: pointer;
    color: #000;
    margin-right: 75px;

    &:hover {
      color: rgb(32, 160, 255);
    }
  }
}

.left-menu-container {
  margin-top: 55px;
  width: 300px;
  min-height: 200px;
  text-align: left;
  border-right: solid 1px #e6e6e6;
  overflow-x: hidden;

  .el-menu {
    width: 100%;
  }
  .el-menu-vertical:not(.el-menu--collapse) {
    max-width: 300px;
    min-height: 400px;
  }

  .is-active {
    border-right: solid 3px rgb(32, 160, 255);
  }
}

.right-content-container {
  width: 100%;
  margin-top: 55px;
}
</style>
